package com.mask.common.mq.service;

import com.mask.common.mq.config.RabbitMQProperties;
import com.mask.common.mq.model.MessageDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.amqp.RabbitTemplateConfigurer;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.UUID;

@Slf4j
@Service
public class MQService {
    @Autowired
    private RabbitTemplate rabbitTemplate;
    
    @Autowired
    private RabbitMQProperties properties;

    /**
     * 发送消息
     */
    public void sendMessage(String exchange, String routingKey, Object message) {
        MessageDTO messageDTO = MessageDTO.builder()
                .messageId(UUID.randomUUID().toString())
                .messageType(message.getClass().getSimpleName())
                .content(message)
                .sendTime(LocalDateTime.now())
                .build();
        
        rabbitTemplate.convertAndSend(exchange, routingKey, messageDTO);
    }

    /**
     * 发送延迟消息
     */
    public void sendDelayMessage(String exchange, String routingKey, Object message, long delayMillis) {
        MessageDTO messageDTO = MessageDTO.builder()
                .messageId(UUID.randomUUID().toString())
                .messageType(message.getClass().getSimpleName())
                .content(message)
                .sendTime(LocalDateTime.now())
                .build();
        
        rabbitTemplate.convertAndSend(exchange, routingKey, messageDTO, msg -> {
            msg.getMessageProperties().setDelay((int) delayMillis);
            return msg;
        });
    }

    /**
     * 发送带有重试机制的消息
     */
    public void sendRetryMessage(String exchange, String routingKey, Object message) {
        for (int i = 0; i < properties.getRetryCount(); i++) {
            try {
                sendMessage(exchange, routingKey, message);
                return;
            } catch (Exception e) {
                log.error("发送消息失败，重试次数：{}", i + 1, e);
                if (i == properties.getRetryCount() - 1) {
                    throw e;
                }
            }
        }
    }
}

// mask:
//   mq:
//     enabled: true
//     retry-count: 3
//     exchanges:
//       order:
//         name: mask.order
//         type: direct
//       notify:
//         name: mask.notify
//         type: fanout
//     queues:
//       order-create:
//         name: mask.order.create
//         exchange: mask.order
//         routing-key: create
//       order-cancel:
//         name: mask.order.cancel
//         exchange: mask.order
//         routing-key: cancel
//       notify:
//         name: mask.notify
//         exchange: mask.notify
//         routing-key: notify

//  @Autowired
//     private MQService mqService;

//     public void createOrder(OrderDTO orderDTO) {
//         // 创建订单
//         Order order = createOrderLogic(orderDTO);
        
//         // 发送订单创建消息
//         mqService.sendMessage("mask.order", "create", order);
//     }

//     public void cancelOrder(Long orderId) {
//         // 取消订单
//         Order order = cancelOrderLogic(orderId);
        
//         // 发送延迟消息，30分钟后检查订单状态
//         mqService.sendDelayMessage("mask.order", "cancel", order, 30 * 60 * 1000);
//     }

// @Component
// public class OrderCreateHandler extends MessageHandler<Order> {
//     @Override
//     protected void process(Order order, MessageDTO messageDTO) {
//         // 处理订单创建后的业务逻辑
//         log.info("处理订单创建消息：orderId={}", order.getId());
//     }
// }

// @Component
// public class OrderCancelHandler extends MessageHandler<Order> {
//     @Override
//     protected void process(Order order, MessageDTO messageDTO) {
//         // 处理订单取消后的业务逻辑
//         log.info("处理订单取消消息：orderId={}", order.getId());
//     }
// }